
const config = require('./config')
const jwt = require('jsonwebtoken')


const allows = [
  {path:'/users/login', method:'POST'},
  {path:'/users/register', method:'POST'},
  {path:'/users/login', method:'GET'},
  {path:'/users/register', method:'GET'},
  {path:'/', method:'GET'}
]


module.exports = async function(ctx, next){

  var filtered = allows.filter((value) => ctx.path === value.path && ctx.method === value.method)

  if(filtered.length !==0 ){
    await next()
    return
  }

//  console.log('---------------------------');
  var auth = ctx.cookies.get('authorization')

  //var auth = ctx.headers['authorization']
  if(!auth) {
    //ctx.throw(403, 'No Authorization cookiet.')
    ctx.response.redirect('/users/login')
    return
  }
    try {
      var user = jwt.verify(auth,config.secretKey)
    } catch (e) {
      ctx.throw(403, 'Invalid token.')
    }

    ctx.currentUser = user.user
    await next()
}
